<?php
/**
 * Created by PhpStorm.
 * User: luzy
 * Date: 2018/4/19
 * Time: 下午3:48
 */

class Postv2 extends Base_Controller
{
    private $_appid;
    private $_appsecret;

    public function __construct()
    {
        parent::__construct();
        $this->load->config('weixin');
        $this->_appid = $this->config->item('nldou_fuwu_appid');
        $this->_appsecret = $this->config->item('nldou_fuwu_appsecret');
    }

    public function scan()
    {
        $get = $this->input->get();
        if (!isset($get['pid'])||empty($get['pid'])||!is_numeric($get['pid'])||
            !isset($get['sls'])||empty($get['sls'])||
            !isset($get['postid'])||empty($get['postid'])||!is_numeric($get['postid'])
        )
            die("error: request forbidden");

        $param = $get['pid'].'.'.$get['sls'].'.'.$get['postid'];

        $scope='snsapi_base';
        $redirect_uri = site_url('/salesman/postv2/scancallback');

        $this->load->library('openlogin/wechat',array('appid'=>$this->_appid,'appsecret'=>$this->_appsecret));
        $this->wechat->set_scope($scope);
        $this->wechat->set_redirect_uri($redirect_uri);
        $this->wechat->set_state($param);
        //跳转到引导页，静默授权
        $this->wechat->get_code();
    }

    public function scancallback()
    {
        $get = $this->input->get();
        if(!isset($get['state'])||empty($get['state']))
            die("error: request forbidden");

        $param = $get['state'];
        $paramarr = explode('.',$param);
        if (!isset($paramarr[0])||empty($paramarr[0])||!is_numeric($paramarr[0])||/*pid*/
            !isset($paramarr[1])||empty($paramarr[1])||/*sls*/
            !isset($paramarr[2])||empty($paramarr[2])||!is_numeric($paramarr[2])/*postid*/
        )
            die("error: request forbidden");
        $pid = $paramarr[0];
        $sls = $paramarr[1];
        $postid = $paramarr[2];

        //获取openid
        $this->load->library('openlogin/wechat',array('appid'=>$this->_appid,'appsecret'=>$this->_appsecret));
        $this->wechat->get_access_token();
        $openid=$this->wechat->get_openid();
        //检查用户是否已经注册
        $this->load->model('user_model');
        $uid=$this->user_model->getUidByWxopenid($openid);
        if($uid !== false){
            $this->load->model('salesman_post_model');
            //检查目标路径
            $url = $this->salesman_post_model->getRedirectPage($pid,$sls);
            if ($url!==false){
                //统计
                $this->salesman_post_model->saveScanStat($pid,$postid,$uid,$sls);
                //跳转目标路径
                redirect($url);
            }else{die("error: request forbidden");}
        }
        //没有注册，获取用户基本信息
        else{
            $this->firstscan($param);
        }
    }

    //第一次登陆
    public function firstscan($param = "")
    {
        if (empty($param)) die("error: request forbidden");
        $paramarr = explode('.',$param);
        if (!isset($paramarr[0])||empty($paramarr[0])||!is_numeric($paramarr[0])||/*pid*/
            !isset($paramarr[1])||empty($paramarr[1])||/*sls*/
            !isset($paramarr[2])||empty($paramarr[2])||!is_numeric($paramarr[2])/*postid*/
        )
            die("error: request forbidden");

        $redirect_uri=site_url('/salesman/postv2/firstscancallback');
        $scope='snsapi_userinfo';
        $this->wechat->set_scope($scope);
        $this->wechat->set_state($param);
        $this->wechat->set_redirect_uri($redirect_uri);
        //跳转到引导页，授权登陆
        $this->wechat->get_code();
    }

    public function firstscancallback()
    {
        $get = $this->input->get();
        if(!isset($get['state'])||empty($get['state']))
            die("error: request forbidden");

        $param = $get['state'];
        $paramarr = explode('.',$param);
        if (!isset($paramarr[0])||empty($paramarr[0])||!is_numeric($paramarr[0])||/*pid*/
            !isset($paramarr[1])||empty($paramarr[1])||/*sls*/
            !isset($paramarr[2])||empty($paramarr[2])||!is_numeric($paramarr[2])/*postid*/
        )
            die("error: request forbidden");
        $pid = $paramarr[0];
        $sls = $paramarr[1];
        $postid = $paramarr[2];

        $this->load->library('openlogin/wechat',array('appid'=>$this->_appid,'appsecret'=>$this->_appsecret));
        $this->wechat->get_access_token();
        $info=$this->wechat->get_user_info();
        //检查用户是否已经注册
        $this->load->model('user_model');
        $res=$this->user_model->getUser(array('wx_unionid'=>$info['unionid']),'uid');

        if($info!==false){
            if (empty($res)){
                //新用户注册
                $data = array(
                    'utype'      => 'weixin',
                    'wx_openid'  => $info['openid'],
                    'wx_unionid' => $info['unionid'],
                    'userName'   => $info['nickname'],
                    'userToken'  => md5($info['access_token']),
                    'userIcon'   => $info['userIcon'],
                    'status'     => 1,
                    'created'    => time(),
                    'changed'    => time()
                );
                $uid = $this->user_model->createUser($data);
                if($uid){
                    $this->user_model->createUserInfo(array('uid' => $uid, 'userGender'=>$info['gender']));

                    $this->load->model('redis_model');
                    $redis = $this->redis_model->getRedisInstance();
                    //设置登陆信息
                    $redis->set('user:'.$info['openid'],$uid);
                    $this->load->model('salesman_post_model');
                    //检查目标路径
                    $url = $this->salesman_post_model->getRedirectPage($pid,$sls);
                    if ($url!==false){
                        //统计
                        $this->salesman_post_model->saveScanStat($pid,$postid,$uid,$sls);
                        //跳转目标路径
                        redirect($url);
                    }else{die("error: request forbidden");}
                }else{die("系统错误，请重试");}
            }else{
                //用户存在
                $data = array(
                    'utype'      => 'weixin',
                    'wx_openid'  => $info['openid'],
                    'wx_unionid' => $info['unionid'],
                    'userName'   => $info['nickname'],
                    'userToken'  => md5($info['access_token']),
                    'userIcon'   => $info['userIcon']
                );
                $this->user_model->editUser($data,array('uid'=>$res['uid']));
                $this->user_model->setUidWithOpenid($info['openid'],$res['uid']);
                //检查目标路径
                $this->load->model('salesman_post_model');
                $url = $this->salesman_post_model->getRedirectPage($pid,$sls);
                if ($url!==false){
                    //统计
                    $this->salesman_post_model->saveScanStat($pid,$postid,$res['uid'],$sls);
                    //跳转目标路径
                    redirect($url);
                }else{die("error: request forbidden");}
            }
        }else{die("系统错误，请重试");}
    }

    public function getPosts()
    {
        $post = $this->input->post();
        if (!isset($post['sls'])||empty($post['sls'])||
            !isset($post['type'])||!is_numeric($post['type']))
            $this->error('param error');

        if (!isset($post['pagesize'])||!is_numeric($post['pagesize'])) $limit=10;
        else $limit = (int)$post['pagesize'];

        if (isset($post['pageno'])&&is_numeric($post['pageno'])) $offset = ((int)$post['pageno']-1)*$limit;
        else $offset = 0;


        $this->load->model('salesman_post_model');
        $res = $this->salesman_post_model->getSlsPosts($post['type'],$post['sls'],$offset,$limit);

        $this->success($res);
    }

    public function getPostType()
    {
        $this->load->model('salesman_post_model');
        $res = $this->salesman_post_model->getPostType();

        $this->success($res);
    }

}